import os
import threading
import time
from datetime import datetime

# from flask import current_app  # 不再需要，由调用者提供上下文
from config import Config
from extensions import db
from logger_config import get_logger
from models import QueryRecord, User, CostRecord, UserStats
from services.agent_service import agent_service
from services.conversation_file_service import ConversationFileService
from services.cost_service import cost_service
from services.summary_service import summary_service
from utils.response_utils import parse_agent_output, generate_execution_summary
from utils.session_utils import get_session_id

logger = get_logger(__name__)


class QueryService:
    """查询服务类，负责处理用户查询请求"""

    def __init__(self):
        self.config = Config()
        self.active_queries = {}  # 存储活跃的查询线程
        self.query_lock = threading.Lock()
        self.conversation_service = ConversationFileService()  # 对话文件服务
        self.conversation_file_service = ConversationFileService()  # 对话文件服务（兼容性）

    def process_query(self, user_id, query_text, session_id=None, model=None):
        """处理用户查询
        
        Args:
            user_id: 用户ID
            query_text: 查询文本
            session_id: 会话ID（可选）
            model: 模型名称（可选）
        
        Returns:
            dict: 查询结果
        """
        try:
            # 确保有会话ID（应该由调用方提供）
            if not session_id:
                logger.warning("QueryService.process_query 收到空的session_id，这不应该发生")
                session_id = get_session_id()

            # 检查是否为简单对话
            from utils.conversation_classifier import is_simple_conversation, get_simple_response
            if session_id == 'simple_conversation' or is_simple_conversation(query_text):
                # 处理简单对话，不需要AI代理
                return self._process_simple_conversation(user_id, query_text, session_id, model)

            # 获取代理实例
            agent = agent_service.get_agent_instance(session_id)
            if not agent:
                # 尝试获取任何可用的代理实例
                available_sessions = agent_service.get_all_sessions()
                if available_sessions:
                    session_id = available_sessions[0]
                    agent = agent_service.get_agent_instance(session_id)
                    logger.info(f"使用可用的代理实例，会话ID: {session_id}")

                if not agent:
                    return {
                        'success': False,
                        'error': '代理实例未初始化，请先初始化代理',
                        'error_code': 'AGENT_NOT_INITIALIZED'
                    }

            # 记录查询开始时间
            start_time = time.time()

            # 创建查询记录（使用实际的session_id）
            query_record = self._create_query_record(user_id, query_text, session_id)

            # 执行查询
            result = self._execute_query(agent, query_text, query_record, start_time)

            # 确保返回结果中包含实际使用的session_id
            if result.get('success'):
                result['session_id'] = session_id

            return result

        except Exception as e:
            logger.error(f"处理查询失败: {str(e)}", exc_info=True)
            return {
                'success': False,
                'error': f'查询处理失败: {str(e)}',
                'error_code': 'QUERY_PROCESSING_ERROR'
            }

    def _create_query_record(self, user_id, query_text, session_id):
        """创建查询记录
        
        Args:
            user_id: 用户ID
            query_text: 查询文本
            session_id: 会话ID
        
        Returns:
            QueryRecord: 查询记录对象
        """
        try:
            query_record = QueryRecord(
                user_id=user_id,
                query=query_text,
                session_id=session_id,
                model=Config.DEFAULT_MODEL,
                status='processing'
            )
            db.session.add(query_record)
            db.session.commit()

            logger.info(f"查询记录已创建，ID: {query_record.id}，用户: {user_id}")
            return query_record

        except Exception as e:
            logger.error(f"创建查询记录失败: {str(e)}")
            db.session.rollback()
            raise

    def _execute_query(self, agent, query_text, query_record, start_time):
        """执行查询
        
        Args:
            agent: 代理实例
            query_text: 查询文本
            query_record: 查询记录
            start_time: 开始时间
        
        Returns:
            dict: 查询结果
        """
        try:
            # 为当前查询创建专属工作目录并固定使用
            original_cwd = os.getcwd()
            session_work_dir = self._prepare_session_work_directory(query_record.user_id, query_record.session_id)

            # 将工作目录信息存储到查询记录中，供后续操作使用
            query_record.work_directory = session_work_dir

            try:
                # 切换到会话专属工作目录
                os.chdir(session_work_dir)
                logger.info(f"切换工作目录到: {session_work_dir}，查询ID: {query_record.id}")

                # 会话工作目录将通过参数传递给agent.go()方法
                logger.info(f"准备传递会话工作目录给agent: {session_work_dir}")

                # 执行代理查询，传递会话工作目录
                logger.info(f"开始执行查询，记录ID: {query_record.id}")
                log, agent_output = agent.go(query_text, session_work_dir=session_work_dir)

            finally:
                # 恢复原始工作目录
                logger.info("恢复工作目录")
                os.chdir(original_cwd)

            # 计算执行时间
            execution_time = time.time() - start_time

            # 解析代理输出
            parsed_output = parse_agent_output(agent_output)

            # 计算成本
            cost_info = cost_service.calculate_query_cost(
                query_text, agent_output, {}
            )

            # 生成基础执行摘要
            execution_summary = generate_execution_summary(
                parsed_output.get('log', []) if isinstance(parsed_output, dict) else [],
                parsed_output,
                query_text,
                execution_time,
                cost_info.get('input_tokens', 0),
                cost_info.get('output_tokens', 0)
            )

            # 生成智能总结
            intelligent_summary = None
            try:
                # 提取解析后的日志用于智能总结
                execution_log = []
                if isinstance(parsed_output, list):
                    execution_log = parsed_output
                elif isinstance(parsed_output, dict) and 'log' in parsed_output:
                    execution_log = parsed_output['log']

                intelligent_summary = summary_service.generate_intelligent_summary(
                    execution_log,
                    query_text,
                    execution_time,
                    parsed_output
                )
                logger.info(f"智能总结生成成功，查询ID: {query_record.id}")
            except Exception as e:
                logger.error(f"智能总结生成失败，查询ID: {query_record.id}: {str(e)}")
                intelligent_summary = None

            # 更新查询记录
            self._update_query_record(
                query_record, agent_output, execution_time,
                cost_info, 'completed'
            )

            # 更新用户统计（在同一个事务中）
            from services.user_stats_service import UserStatsService
            user_stats = UserStatsService.get_or_create_user_stats_no_commit(query_record.user_id)
            
            # 直接更新统计数据
            user_stats.total_queries += 1
            user_stats.successful_queries += 1
            
            # 更新模型使用统计
            model_name = query_record.model or cost_info.get('model_name', Config.DEFAULT_MODEL)
            if not user_stats.model_usage:
                user_stats.model_usage = {}
            model_count = user_stats.model_usage.get(model_name, 0)
            user_stats.model_usage[model_name] = model_count + 1
            
            # 更新token统计
            user_stats.total_input_tokens += cost_info.get('input_tokens', 0)
            user_stats.total_output_tokens += cost_info.get('output_tokens', 0)
            user_stats.total_tokens += cost_info.get('input_tokens', 0) + cost_info.get('output_tokens', 0)
            
            # 更新时间统计
            if execution_time > 0:
                user_stats.total_duration += execution_time
                user_stats.avg_duration = user_stats.total_duration / user_stats.total_queries
                
            # 更新费用统计
            user_stats.total_cost += cost_info.get('total_cost', 0.0)
                
            # 更新最后活动时间
            user_stats.last_query_at = datetime.utcnow()
            user_stats.updated_at = datetime.utcnow()

            # 保存对话文件到本地 - 统一使用add_message_to_session方法
            try:
                # 提取执行日志
                execution_log = []
                if isinstance(parsed_output, list):
                    execution_log = parsed_output
                elif isinstance(parsed_output, dict) and 'log' in parsed_output:
                    execution_log = parsed_output['log']

                # 使用统一的会话保存方法
                conversation_session = self.conversation_service.add_message_to_session(
                    user_id=query_record.user_id,
                    session_id=query_record.session_id,
                    request_id=str(query_record.id),
                    query_text=query_text,
                    response_text=agent_output,
                    log_data=execution_log,
                    tokens=cost_info.get('input_tokens', 0) + cost_info.get('output_tokens', 0),
                    cost=cost_info.get('total_cost', 0.0)
                )

                # 单独保存执行过程数据，供前端回显使用
                self._save_execution_process(query_record.session_id, query_record.id, execution_log, parsed_output)

                # 归档下载的文件到对话目录中，使用固定的工作目录
                work_dir = getattr(query_record, 'work_directory', None)
                self._archive_query_downloads(query_record.user_id, query_record.session_id, query_record.id, work_dir)

                logger.info(f"对话文件已保存，记录ID: {query_record.id}，会话ID: {query_record.session_id}")
            except Exception as e:
                logger.error(f"保存对话文件失败，记录ID: {query_record.id}: {str(e)}")
                # 保存失败不影响查询结果返回

            logger.info(f"查询执行完成，记录ID: {query_record.id}，耗时: {execution_time:.2f}秒")

            return {
                'success': True,
                'result': parsed_output,
                'execution_summary': execution_summary,
                'intelligent_summary': intelligent_summary,
                'cost_info': cost_info,
                'execution_time': execution_time,
                'query_id': query_record.id
            }

        except Exception as e:
            # 更新查询记录为失败状态
            self._update_query_record(
                query_record, None, time.time() - start_time,
                None, 'failed', str(e)
            )

            logger.error(f"查询执行失败，记录ID: {query_record.id}: {str(e)}")
            raise

    def _update_query_record(self, query_record, response, execution_time,
                             cost_info, status, error_message=None):
        """更新查询记录
        
        Args:
            query_record: 查询记录对象
            response: 代理响应
            execution_time: 执行时间
            cost_info: 成本信息
            status: 状态
            error_message: 错误信息（可选）
        """
        try:
            query_record.response = response
            query_record.duration = execution_time
            query_record.status = status

            if cost_info:
                query_record.input_tokens = cost_info.get('input_tokens', 0)
                query_record.output_tokens = cost_info.get('output_tokens', 0)
                query_record.total_tokens = cost_info.get('input_tokens', 0) + cost_info.get('output_tokens', 0)
                
                # 创建费用记录（如果不存在）
                if not query_record.cost_record and status == 'completed':
                    cost_record = CostRecord(
                        user_id=query_record.user_id,
                        request_id=query_record.id,
                        model=query_record.model or cost_info.get('model_name', Config.DEFAULT_MODEL),
                        input_tokens=cost_info.get('input_tokens', 0),
                        output_tokens=cost_info.get('output_tokens', 0),
                        input_cost=cost_info.get('input_cost', 0.0),
                        output_cost=cost_info.get('output_cost', 0.0),
                        cost=cost_info.get('total_cost', 0.0)
                    )
                    db.session.add(cost_record)

            if error_message:
                query_record.error_message = error_message

            db.session.commit()

        except Exception as e:
            logger.error(f"更新查询记录失败: {str(e)}")
            db.session.rollback()

    def _update_user_stats(self, user_id, cost_info):
        """更新用户统计信息
        
        Args:
            user_id: 用户ID
            cost_info: 成本信息
        """
        try:
            # 获取或创建用户统计记录
            user_stats = UserStats.query.filter_by(user_id=user_id).first()
            if not user_stats:
                user_stats = UserStats(user_id=user_id)
                db.session.add(user_stats)
                # 刷新以确保默认值被设置
                db.session.flush()

            if cost_info:
                # 确保字段不为 None
                user_stats.total_queries = (user_stats.total_queries or 0) + 1
                user_stats.total_cost = (user_stats.total_cost or 0.0) + cost_info.get('total_cost', 0.0)
                user_stats.total_input_tokens = (user_stats.total_input_tokens or 0) + cost_info.get('input_tokens', 0)
                user_stats.total_output_tokens = (user_stats.total_output_tokens or 0) + cost_info.get('output_tokens',
                                                                                                       0)
                user_stats.total_tokens = (user_stats.total_tokens or 0) + cost_info.get('input_tokens',
                                                                                         0) + cost_info.get(
                    'output_tokens', 0)
                user_stats.last_query_at = datetime.utcnow()
                
                db.session.commit()
                logger.info(f"用户统计已更新，用户ID: {user_id}")

        except Exception as e:
            logger.error(f"更新用户统计失败: {str(e)}")
            db.session.rollback()

    def _save_execution_process(self, session_id: str, query_id: int, execution_log: list, parsed_output: dict):
        """单独保存执行过程数据，供前端回显使用
        
        Args:
            session_id: 会话ID
            query_id: 查询ID
            execution_log: 执行日志
            parsed_output: 解析后的输出
        """
        try:
            # 构建执行过程数据
            execution_process = {
                'query_id': query_id,
                'session_id': session_id,
                'timestamp': datetime.utcnow().isoformat(),
                'execution_steps': execution_log,
                'final_output': parsed_output,
                'step_count': len(execution_log) if execution_log else 0
            }

            # 保存到conversation_file_service的执行过程存储中
            self.conversation_service.save_execution_process(
                session_id=session_id,
                query_id=str(query_id),
                execution_data=execution_process
            )

            logger.info(f"执行过程数据已保存，查询ID: {query_id}，会话ID: {session_id}")

        except Exception as e:
            logger.error(f"保存执行过程数据失败，查询ID: {query_id}: {str(e)}")
            # 执行过程保存失败不影响主流程

    def _prepare_session_work_directory(self, user_id: int, session_id: str):
        """为会话准备专属工作目录
        
        Args:
            user_id: 用户ID
            session_id: 会话ID
            
        Returns:
            str: 会话工作目录路径
        """
        try:
            # 获取会话的对话目录
            session_record = self.conversation_file_service.get_or_create_session(user_id, session_id)
            logger.info(f"[DEBUG] 获取会话记录: session_record={session_record}, conversation_dir={session_record.conversation_dir if session_record else None}")
            
            if session_record and session_record.conversation_dir:
                # 在对话目录下创建工作目录
                work_dir = os.path.join(session_record.conversation_dir, 'workspace')
                logger.info(f"[DEBUG] 使用会话目录创建工作目录: {work_dir}")
            else:
                # 备用方案：在临时目录下创建
                from config import Config
                base_storage_dir = getattr(Config, 'CONVERSATION_STORAGE_DIR', 'conversation_data')
                work_dir = os.path.join(base_storage_dir, 'temp_workspaces', session_id)
                logger.info(f"[DEBUG] 使用备用方案创建工作目录: {work_dir}")

            # 确保目录存在
            os.makedirs(work_dir, exist_ok=True)
            logger.info(f"准备会话工作目录: {work_dir}")

            return work_dir

        except Exception as e:
            logger.error(f"准备会话工作目录失败: {str(e)}")
            # 强制使用备用方案而不是当前工作目录
            from config import Config
            base_storage_dir = getattr(Config, 'CONVERSATION_STORAGE_DIR', 'conversation_data')
            fallback_work_dir = os.path.join(base_storage_dir, 'temp_workspaces', session_id)
            os.makedirs(fallback_work_dir, exist_ok=True)
            logger.info(f"[DEBUG] 异常处理：使用强制备用工作目录: {fallback_work_dir}")
            return fallback_work_dir

    def _archive_query_downloads(self, user_id: int, session_id: str, query_id: int, work_directory: str = None):
        """归档查询产生的下载文件
        
        Args:
            user_id: 用户ID
            session_id: 会话ID
            query_id: 查询ID
            work_directory: 指定的工作目录路径，如果不提供则使用会话工作目录
        """
        try:
            # 使用指定的工作目录，如果没有则获取会话工作目录
            if work_directory and os.path.exists(work_directory):
                download_dir = work_directory
            else:
                download_dir = self._prepare_session_work_directory(user_id, session_id)

            logger.info(f"开始归档下载文件，目录: {download_dir}，查询ID: {query_id}")

            # 检查目录是否存在
            if not os.path.exists(download_dir):
                logger.info(f"工作目录不存在，跳过归档: {download_dir}")
                return

            # 查找可能的下载文件（常见的下载文件扩展名）
            download_extensions = ['.csv', '.xlsx', '.json', '.txt', '.pdf', '.png', '.jpg', '.zip']

            # 检查目录中是否有下载文件
            has_downloads = False
            for root, dirs, files in os.walk(download_dir):
                for file in files:
                    if any(file.lower().endswith(ext) for ext in download_extensions):
                        has_downloads = True
                        break
                if has_downloads:
                    break

            if has_downloads:
                # 归档下载文件
                archived_files = self.conversation_service.archive_downloaded_files(
                    session_id=session_id,
                    query_id=str(query_id),
                    download_dir=download_dir
                )
                archived_files_count = len(archived_files)

                if archived_files_count > 0:
                    logger.info(f"已归档 {archived_files_count} 个下载文件，查询ID: {query_id}，会话ID: {session_id}")
                else:
                    logger.info(f"未找到需要归档的文件，查询ID: {query_id}")
            else:
                logger.info(f"工作目录中未发现下载文件，查询ID: {query_id}")

        except Exception as e:
            logger.error(f"归档下载文件失败，查询ID: {query_id}: {str(e)}")
            # 归档失败不影响主流程

    def get_query_history(self, user_id, limit=50, offset=0):
        """获取用户查询历史
        
        Args:
            user_id: 用户ID
            limit: 限制数量
            offset: 偏移量
        
        Returns:
            list: 查询历史列表
        """
        try:
            queries = db.session.query(QueryRecord).filter_by(user_id=user_id) \
                .order_by(QueryRecord.created_at.desc()) \
                .limit(limit) \
                .offset(offset) \
                .all()

            result = []
            for q in queries:
                query_info = {
                    'id': q.id,
                    'query': q.query,
                    'response': q.response,
                    'timestamp': q.created_at.isoformat() if q.created_at else None,
                    'execution_time': q.duration,
                    'status': q.status,
                    'total_cost': q.cost_record.cost if q.cost_record else 0.0,
                    'input_tokens': q.input_tokens,
                    'output_tokens': q.output_tokens,
                    'error_message': q.error_message,
                    'session_id': q.session_id
                }
                
                # 检查是否有执行过程数据
                if q.session_id:
                    try:
                        execution_data = self.conversation_service.get_execution_process(
                            session_id=q.session_id,
                            query_id=str(q.id)
                        )
                        query_info['has_execution_data'] = execution_data is not None
                        if execution_data:
                            query_info['step_count'] = execution_data.get('step_count', 0)
                    except Exception:
                        query_info['has_execution_data'] = False
                else:
                    query_info['has_execution_data'] = False
                
                result.append(query_info)
            
            return result

        except Exception as e:
            logger.error(f"获取查询历史失败: {str(e)}")
            return []

    def get_query_by_id(self, query_id, user_id=None):
        """根据ID获取查询记录
        
        Args:
            query_id: 查询ID
            user_id: 用户ID（可选，用于权限验证）
        
        Returns:
            dict: 查询记录，如果不存在返回None
        """
        try:
            query = db.session.query(QueryRecord).filter_by(id=query_id)

            # 如果提供了用户ID，则验证权限
            if user_id:
                query = query.filter_by(user_id=user_id)

            query = query.first()

            if not query:
                return None

            # 基础查询信息
            result = {
                'id': query.id,
                'query': query.query,
                'response': query.response,
                'timestamp': query.created_at.isoformat() if query.created_at else None,
                'execution_time': query.duration,
                'status': query.status,
                'total_cost': query.cost_record.cost if query.cost_record else 0.0,
                'input_tokens': query.input_tokens,
                'output_tokens': query.output_tokens,
                'error_message': query.error_message,
                'session_id': query.session_id
            }
            
            # 尝试加载执行过程数据（如果存在session_id）
            if query.session_id:
                try:
                    execution_data = self.conversation_service.get_execution_process(
                        session_id=query.session_id,
                        query_id=str(query.id)
                    )
                    if execution_data:
                        result['execution_data'] = execution_data
                        result['has_execution_data'] = True
                        # 添加执行步骤的简要信息
                        result['step_count'] = execution_data.get('step_count', 0)
                        result['intermediate_steps'] = execution_data.get('intermediate_steps', [])
                        result['log_data'] = execution_data.get('log_data', [])
                    else:
                        result['has_execution_data'] = False
                except Exception as exec_error:
                    logger.warning(f"加载执行过程数据失败，查询ID: {query_id}: {str(exec_error)}")
                    result['has_execution_data'] = False
            else:
                result['has_execution_data'] = False

            return result

        except Exception as e:
            logger.error(f"获取查询记录失败: {str(e)}")
            return None

    def delete_query(self, query_id, user_id):
        """删除查询记录
        
        Args:
            query_id: 查询ID
            user_id: 用户ID
        
        Returns:
            bool: 是否成功删除
        """
        try:
            query = db.session.query(QueryRecord).filter_by(id=query_id, user_id=user_id).first()

            if not query:
                return False

            db.session.delete(query)
            db.session.commit()

            logger.info(f"查询记录已删除，ID: {query_id}，用户: {user_id}")
            return True

        except Exception as e:
            logger.error(f"删除查询记录失败: {str(e)}")
            db.session.rollback()
            return False

    def get_user_query_stats(self, user_id, days=30):
        """获取用户查询统计信息
        
        Args:
            user_id: 用户ID
            days: 统计天数
            
        Returns:
            dict: 统计信息
        """
        try:
            from datetime import datetime, timedelta
            
            end_date = datetime.now()
            start_date = end_date - timedelta(days=days)
            
            # 查询统计信息
            stats = db.session.query(
                db.func.count(QueryRecord.id).label('total_queries'),
                db.func.sum(CostRecord.cost).label('total_cost'),
                db.func.sum(QueryRecord.input_tokens + QueryRecord.output_tokens).label('total_tokens'),
                db.func.avg(QueryRecord.duration).label('avg_execution_time')
            ).outerjoin(CostRecord, QueryRecord.id == CostRecord.request_id).filter(
                QueryRecord.user_id == user_id,
                QueryRecord.created_at >= start_date,
                QueryRecord.created_at <= end_date
            ).first()
            
            # 按日期分组的查询数量
            daily_stats = db.session.query(
                db.func.date(QueryRecord.created_at).label('date'),
                db.func.count(QueryRecord.id).label('count')
            ).filter(
                QueryRecord.user_id == user_id,
                QueryRecord.created_at >= start_date,
                QueryRecord.created_at <= end_date
            ).group_by(db.func.date(QueryRecord.created_at)).all()
            
            return {
                'total_queries': stats.total_queries or 0,
                'total_cost': float(stats.total_cost or 0),
                'total_tokens': stats.total_tokens or 0,
                'avg_execution_time': float(stats.avg_execution_time or 0),
                'daily_stats': [
                    {
                        'date': stat.date.strftime('%Y-%m-%d') if hasattr(stat.date, 'strftime') else str(stat.date),
                        'count': stat.count
                    } for stat in daily_stats
                ]
            }
            
        except Exception as e:
            logger.error(f"获取用户查询统计失败: {str(e)}")
            return {
                'total_queries': 0,
                'total_cost': 0.0,
                'total_tokens': 0,
                'avg_execution_time': 0.0,
                'daily_stats': []
            }

    def _process_simple_conversation(self, user_id, query_text, session_id, model=None):
        """处理简单对话
        
        Args:
            user_id: 用户ID
            query_text: 查询文本
            session_id: 会话ID
            model: 模型名称（可选）
        
        Returns:
            dict: 查询结果
        """
        try:
            from utils.conversation_classifier import get_simple_response

            # 记录查询开始时间
            start_time = time.time()

            # 创建查询记录
            query_record = self._create_query_record(user_id, query_text, session_id)

            # 生成简单回复
            simple_reply = get_simple_response(query_text)

            # 计算执行时间
            execution_time = time.time() - start_time

            # 确定使用的模型名称
            model_name = model or 'simple_response'  # 如果没有指定模型，使用默认的simple_response
            
            # 更新查询记录
            query_record.response = simple_reply
            query_record.status = 'completed'
            query_record.completed_at = datetime.utcnow()
            query_record.execution_time = execution_time
            query_record.model = model_name

            # 计算简单对话的token和费用
            cost_info = cost_service.calculate_query_cost(
                query_text=query_text,
                response_text=simple_reply,
                model_name=model_name
            )
            
            # 更新查询记录的token信息
            query_record.input_tokens = cost_info.get('input_tokens', 0)
            query_record.output_tokens = cost_info.get('output_tokens', 0)
            query_record.total_tokens = cost_info.get('input_tokens', 0) + cost_info.get('output_tokens', 0)
            
            # 创建费用记录
            if not query_record.cost_record:
                cost_record = CostRecord(
                    user_id=user_id,
                    request_id=query_record.id,
                    model=model_name,
                    input_tokens=cost_info.get('input_tokens', 0),
                    output_tokens=cost_info.get('output_tokens', 0),
                    input_cost=cost_info.get('input_cost', 0.0),
                    output_cost=cost_info.get('output_cost', 0.0),
                    cost=cost_info.get('total_cost', 0.0)
                )
                db.session.add(cost_record)
            
            # 更新用户统计（在同一个事务中）
            from services.user_stats_service import UserStatsService
            user_stats = UserStatsService.get_or_create_user_stats_no_commit(user_id)
            
            # 直接更新统计数据
            user_stats.total_queries += 1
            user_stats.successful_queries += 1
            
            # 更新模型使用统计
            if not user_stats.model_usage:
                user_stats.model_usage = {}
            model_count = user_stats.model_usage.get(model_name, 0)
            user_stats.model_usage[model_name] = model_count + 1
            
            # 更新token统计
            user_stats.total_input_tokens += cost_info.get('input_tokens', 0)
            user_stats.total_output_tokens += cost_info.get('output_tokens', 0)
            user_stats.total_tokens += cost_info.get('input_tokens', 0) + cost_info.get('output_tokens', 0)
            
            # 更新时间统计
            if execution_time > 0:
                user_stats.total_duration += execution_time
                user_stats.avg_duration = user_stats.total_duration / user_stats.total_queries
                
            # 更新费用统计
            user_stats.total_cost += cost_info.get('total_cost', 0.0)
                
            # 更新最后活动时间
            user_stats.last_query_at = datetime.utcnow()
            user_stats.updated_at = datetime.utcnow()
            
            # 统一提交所有更改
            db.session.commit()

            # 保存对话文件
            try:
                self.conversation_service.add_message_to_session(
                    user_id=user_id,
                    session_id=session_id,
                    request_id=str(query_record.id),
                    query_text=query_text,
                    response_text=simple_reply,
                    log_data=[{"type": "simple_conversation", "message": "简单对话处理", "session_id": session_id}],
                    tokens=cost_info.get('input_tokens', 0) + cost_info.get('output_tokens', 0),
                    cost=cost_info.get('total_cost', 0.0)
                )
                logger.info(f"简单对话文件保存成功，用户: {user_id}，会话: {session_id}，记录ID: {query_record.id}")
            except Exception as e:
                logger.error(f"简单对话文件保存失败: {str(e)}")

            return {
                'success': True,
                'response': simple_reply,
                'query_id': query_record.id,
                'execution_time': execution_time,
                'model': 'simple_response'
            }

        except Exception as e:
            logger.error(f"处理简单对话失败: {str(e)}", exc_info=True)
            # 如果有查询记录，标记为失败
            if 'query_record' in locals() and query_record:
                query_record.status = 'failed'
                query_record.error_message = str(e)
                query_record.completed_at = datetime.utcnow()
                try:
                    db.session.commit()
                except:
                    db.session.rollback()

            return {
                'success': False,
                'error': f'简单对话处理失败: {str(e)}',
                'error_code': 'SIMPLE_CONVERSATION_ERROR'
            }


# 全局查询服务实例
query_service = QueryService()
